import { getUser } from '@/app/storage'
import { getRouteMenus } from '@/apis/system'
import { LAYOUT_NAME, ERROR_NAME } from '@/const/router'
import useAuthStore from '@/store/modules/auth'
import router from '../index'

const modules = import.meta.glob('@/views/**/*.vue')

// 懒加载引入组件
export function lazyLoadComponent(component) {
  if (component) {
    for (const path in modules) {
      const dir = path.split('views')[1].split('.vue')[0]
      if (dir === component || dir === component + '/index') {
        return () => modules[path]()
      }
    }
  }

  return () => import('@/views/exception/empty.vue')
}

// 过滤树
export function treeFilter(tree, fn) {
  return tree
    .map((node) => ({ ...node }))
    .filter((node) => {
      node.children = node.children && treeFilter(node.children, fn)
      return fn(node) || (node.children && node.children.length)
    })
}

// 路由扁平化
export function flatRoutes(routes, breadcrumb = []) {
  let result = []
  routes.forEach((route) => {
    const tmp = { ...route }
    if (tmp.children) {
      let childrenBreadcrumb = [...breadcrumb]
      childrenBreadcrumb.push(route)
      let tmpRoute = { ...route }
      tmpRoute.meta.breadcrumb = childrenBreadcrumb
      delete tmpRoute.children
      result.push(tmpRoute)
      let childrenRoutes = flatRoutes(tmp.children, childrenBreadcrumb)
      childrenRoutes.map((item) => result.push(item))
    } else {
      let tmpBreadcrumb = [...breadcrumb]
      tmpBreadcrumb.push(tmp)
      tmp.meta.breadcrumb = tmpBreadcrumb
      result.push(tmp)
    }
  })

  return result
}

// 生成路由
export function generateRouter(routes) {
  const result = []
  routes.forEach((item) => {
    // MAP转路由对象
    const route = {
      path: item.path,
      name: item.name,
      meta: item?.meta || {},
      redirect: item.redirect ? item.redirect : '',
      children: item.children ? generateRouter(item.children) : null,
      component: lazyLoadComponent(item.component),
    }
    result.push(route)
  })

  return result
}

// 处理动态路由菜单
export async function getDynamicMenus() {
  const res = await getRouteMenus()
  const userInfo = getUser()
  const userMenu = treeFilter([], (node) => {
    return node.meta.role
      ? node.meta.role.filter((item) => userInfo.role.indexOf(item) > -1)
          .length > 0
      : true
  })
  const menus = [...userMenu, ...res.list]

  return menus
}

// 初始化路由
export async function initDynamicRouter() {
  try {
    const authStore = useAuthStore()
    const menus = await authStore.getAuthMenuList()
    let dynamicRouter = generateRouter(menus)
    dynamicRouter = flatRoutes(dynamicRouter)
    dynamicRouter.forEach((item) => router.addRoute(LAYOUT_NAME, item))
  } catch (error) {
    router.replace(ERROR_NAME)
  }
}
